package com.bjpowernode.crm.workbench.web.controller;

import com.bjpowernode.crm.commons.contants.Constants;
import com.bjpowernode.crm.commons.domain.ResultEntity;
import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.UserService;
import com.bjpowernode.crm.workbench.domain.Activity;
import com.bjpowernode.crm.workbench.domain.ActivityRemark;
import com.bjpowernode.crm.workbench.service.ActivityRemarkService;
import com.bjpowernode.crm.workbench.service.ActivityService;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 郭俊才
 * 2021/8/22
 */
@Controller
public class ActivityController {
    @Autowired
    private ActivityService activityService;
    @Autowired
    private UserService userService;
    @Autowired
    private ActivityRemarkService activityRemarkService;

    @ResponseBody
    @RequestMapping("/workbench/activity/getPageInfo.do")
    public ResultEntity getPageInfo(Activity activity, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        PageInfo<Activity> pageInfo = activityService.queryByConditions(activity, pageNum, pageSize);
        if (pageInfo.getList() != null) {
            return ResultEntity.successWithData(pageInfo);
        } else {
            return ResultEntity.failed("没有数据!");
        }
    }

    //进入市场活动页面请求用户信息
    @RequestMapping("/workbench/actity/index.do")
    public String toActity(Model model, HttpSession session) {
        List<User> users = userService.queryAllUser();
        List<User> userList = userService.queryAllUser();
        User user = (User) session.getAttribute(Constants.MESSAGE_SESSION_NAME);
        //移除掉当前用户的信息，当前用户的信息从session域中取
        for (int i = 0; i < users.size(); i++) {
            if (user.getId().equals(users.get(i).getId())) {
                users.remove(i);
                break;
            }
        }
        model.addAttribute("users", users);
        model.addAttribute("userList", userList);
        return "workbench/activity/index";
    }

    //添加
    @RequestMapping("/workbench/actity/createActivity.do")
    @ResponseBody
    public ResultEntity createActivity(Activity activity, HttpSession session) {
        User user = (User) session.getAttribute(Constants.MESSAGE_SESSION_NAME);
        activity.setCreateBy(user.getId());
        int i = activityService.saveSelective(activity);
        if (i > 0) {
            return ResultEntity.successWithoutData();
        } else {
            return ResultEntity.failed("添加失败");
        }
    }

    @RequestMapping("/workbench/actity/dropActivity.do")
    @ResponseBody
    public ResultEntity dropActivity(@RequestBody String[] ids) {
        int i = activityService.removeList(ids);
        if (i > 0) {
            return ResultEntity.successWithoutData();
        } else {
            return ResultEntity.failed("删除失败");
        }
    }

    @RequestMapping("/workbench/actity/changeActivity.do")
    @ResponseBody
    public ResultEntity changeActivity(Activity activity, HttpSession session) {
        //设置修改人
        User user = (User) session.getAttribute(Constants.MESSAGE_SESSION_NAME);
        activity.setEditBy(user.getId());
        int i = activityService.editByPrimaryKeySelective(activity);
        if (i > 0) {
            return ResultEntity.successWithoutData();
        } else {
            return ResultEntity.failed("修改失败");
        }
    }

    @RequestMapping("/workbench/actity/getActivity.do")
    @ResponseBody
    public ResultEntity getActivity(String id) {
        Activity activity = activityService.queryByPrimaryKey(id);
        if (activity != null) {
            return ResultEntity.successWithData(activity);
        } else {
            return ResultEntity.failed("查询失败");
        }
    }

    @RequestMapping("/workbench/actity/getActivityForDetails.do")
    public String getActivityForDetails(String id, Model model) {
        //获取市场活动详情
        Activity activity = activityService.queryByPrimaryKeyForDetails(id);
        model.addAttribute("activity", activity);
        //获取市场活动评论评论信息
        List<ActivityRemark> remarkList = activityRemarkService.queryByConditions(new ActivityRemark(null, null, null, null, null, null, null, id));
        model.addAttribute("remarkList", remarkList);
        return "workbench/activity/detail";
    }

    @RequestMapping("/workbench/actity/exportActivityAll.do")
    public void exportActivityAll(HttpServletResponse response, HttpServletRequest request) throws Exception {
        //获取所有市场活动
        List<Activity> activityList = activityService.queryAll();
        //获取工作簿对象
        HSSFWorkbook wb = new HSSFWorkbook();
        //获取工作表对象
        HSSFSheet sheet = wb.createSheet("市场活动详细信息");
        //获取工作表中第一行对象，填充标题
        HSSFRow row = sheet.createRow(0);
        //获取第一行第一列的单元格对象
        HSSFCell cell = row.createCell(0);
        //给第一行第一列的单元格对象设置值
        cell.setCellValue("所有者");
        //给第一行第二列的单元格对象设置值
        cell = row.createCell(1);
        cell.setCellValue("活动名称");
        cell = row.createCell(2);
        cell.setCellValue("开始时间");
        cell = row.createCell(3);
        cell.setCellValue("结束时间");
        cell = row.createCell(4);
        cell.setCellValue("花费");
        cell = row.createCell(5);
        cell.setCellValue("活动描述信息");
        cell = row.createCell(6);
        cell.setCellValue("活动创建时间");
        cell = row.createCell(7);
        cell.setCellValue("活动创建人");
        cell = row.createCell(8);
        cell.setCellValue("活动修改时间");
        cell = row.createCell(9);
        cell.setCellValue("活动修改人");
        //填充数据到Excel文件中
        if (activityList != null) {
            Activity activity = null;
            for (int i = 0; i < activityList.size(); i++) {
                activity = activityList.get(i);
                //获取每一行的行对象
                row = sheet.createRow(i + 1);
                //获取每行的单元格对象
                cell = row.createCell(0);
                cell.setCellValue(activity.getOwner());
                cell = row.createCell(1);
                cell.setCellValue(activity.getName());
                cell = row.createCell(2);
                cell.setCellValue(activity.getStartDate());
                cell = row.createCell(3);
                cell.setCellValue(activity.getEndDate());
                cell = row.createCell(4);
                cell.setCellValue(activity.getCost());
                cell = row.createCell(5);
                cell.setCellValue(activity.getDescription());
                cell = row.createCell(6);
                cell.setCellValue(activity.getCreateTime());
                cell = row.createCell(7);
                cell.setCellValue(activity.getCreateBy());
                cell = row.createCell(8);
                cell.setCellValue(activity.getEditTime());
                cell = row.createCell(9);
                cell.setCellValue(activity.getEditBy());
            }
        }
        //返回响应信息
        //1.设置响应类型
        response.setContentType("application/octet-stream;charset=UTF-8");
        //根据HTTP协议的规定，浏览器每次向服务器发送请求，都会把浏览器信息以请求头的形式发送到服务器
        String browser = request.getHeader("User-Agent");

        //不同的浏览器接收响应头采用的编码格式不一样：
        //IE采用 urlencoded
        ////火狐采用 ISO8859-1
        String fileName = URLEncoder.encode("市场活动列表", "UTF-8");
        if (browser.contains("firefox")) {
            //火狐采用 ISO8859-1
            fileName = new String("市场活动列表".getBytes("UTF-8"), "ISO8859-1");
        }

        //默认情况下，浏览器接收到响应信息之后，直接在显示窗口中打开；
        //可以设置响应头信息，使浏览器接收到响应信息之后，在下载窗口打开,attachment附件
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        //2.获取输出流
        OutputStream os2 = response.getOutputStream();
        //3.把excel文件通过os2输出到客户端
        wb.write(os2);
        //4.关闭资源
        os2.flush();
        wb.close();
    }

    @RequestMapping("/workbench/actity/exportActivityTemplate.do")
    public void exportActivityTemplate(HttpServletResponse response, HttpServletRequest request) throws Exception {
        //获取工作簿对象
        HSSFWorkbook wb = new HSSFWorkbook();
        //获取工作表对象
        HSSFSheet sheet = wb.createSheet("市场活动模板表");
        //获取工作表中第一行对象，填充标题
        HSSFRow row = sheet.createRow(0);
        //获取第一行第一列的单元格对象
        HSSFCell cell = row.createCell(0);
        //给第一行第一列的单元格对象设置值
        cell.setCellValue("活动名称");
        //给第一行第二列的单元格对象设置值
        cell = row.createCell(1);
        cell.setCellValue("开始时间(日期必须转换成文本)");
        cell = row.createCell(2);
        cell.setCellValue("结束时间(日期必须转换成文本)");
        cell = row.createCell(3);
        cell.setCellValue("花费");
        cell = row.createCell(4);
        cell.setCellValue("活动描述");
        //获取第二行的行对象
        row = sheet.createRow(1);
        //获取第二行的每列单元格对象
        cell = row.createCell(0);
        cell.setCellValue("车展");
        cell = row.createCell(1);
        cell.setCellValue("2021-09-09");
        cell = row.createCell(2);
        cell.setCellValue("2020-09-19");
        cell = row.createCell(3);
        cell.setCellValue("2000");
        cell = row.createCell(4);
        cell.setCellValue("这是一次史无前例的车展，快来看吧!");
        //返回响应信息
        //1.设置响应类型
        response.setContentType("application/octet-stream;charset=UTF-8");
        //根据HTTP协议的规定，浏览器每次向服务器发送请求，都会把浏览器信息以请求头的形式发送到服务器
        String browser = request.getHeader("User-Agent");

        //设置下载文件名是中文的乱码问题
        //不同的浏览器接收响应头采用的编码格式不一样：
        //IE采用 urlencoded
        ////火狐采用 ISO8859-1
        String fileName = URLEncoder.encode("市场活动列表上传模板", "UTF-8");
        if (browser.contains("firefox")) {
            //火狐采用 ISO8859-1
            fileName = new String("市场活动列表上传模板".getBytes("UTF-8"), "ISO8859-1");
        }

        //默认情况下，浏览器接收到响应信息之后，直接在显示窗口中打开；
        //可以设置响应头信息，使浏览器接收到响应信息之后，在下载窗口打开,attachment附件
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        //2.获取输出流
        OutputStream os2 = response.getOutputStream();
        //3.把excel文件通过os2输出到客户端
        wb.write(os2);
        //4.关闭资源
        os2.flush();
        wb.close();

    }

    @RequestMapping("/workbench/actity/exportActivitySelective.do")
    public void exportActivitySelective(String[] ids, HttpServletResponse response, HttpServletRequest request) throws Exception {
        List<Activity> activityList = activityService.queryByIds(ids);
        //获取工作簿对象
        HSSFWorkbook wb = new HSSFWorkbook();
        //获取工作表对象
        HSSFSheet sheet = wb.createSheet("市场活动详细信息");
        //获取工作表中第一行对象，填充标题
        HSSFRow row = sheet.createRow(0);
        //获取第一行第一列的单元格对象
        HSSFCell cell = row.createCell(0);
        //给第一行第一列的单元格对象设置值
        cell.setCellValue("所有者");
        //给第一行第二列的单元格对象设置值
        cell = row.createCell(1);
        cell.setCellValue("活动名称");
        cell = row.createCell(2);
        cell.setCellValue("开始时间");
        cell = row.createCell(3);
        cell.setCellValue("结束时间");
        cell = row.createCell(4);
        cell.setCellValue("花费");
        cell = row.createCell(5);
        cell.setCellValue("活动描述信息");
        cell = row.createCell(6);
        cell.setCellValue("活动创建时间");
        cell = row.createCell(7);
        cell.setCellValue("活动创建人");
        cell = row.createCell(8);
        cell.setCellValue("活动修改时间");
        cell = row.createCell(9);
        cell.setCellValue("活动修改人");
        //填充数据到Excel文件中
        if (activityList != null) {
            Activity activity = null;
            for (int i = 0; i < activityList.size(); i++) {
                activity = activityList.get(i);
                //获取每一行的行对象
                row = sheet.createRow(i + 1);
                //获取每行的单元格对象
                cell = row.createCell(0);
                cell.setCellValue(activity.getOwner());
                cell = row.createCell(1);
                cell.setCellValue(activity.getName());
                cell = row.createCell(2);
                cell.setCellValue(activity.getStartDate());
                cell = row.createCell(3);
                cell.setCellValue(activity.getEndDate());
                cell = row.createCell(4);
                cell.setCellValue(activity.getCost());
                cell = row.createCell(5);
                cell.setCellValue(activity.getDescription());
                cell = row.createCell(6);
                cell.setCellValue(activity.getCreateTime());
                cell = row.createCell(7);
                cell.setCellValue(activity.getCreateBy());
                cell = row.createCell(8);
                cell.setCellValue(activity.getEditTime());
                cell = row.createCell(9);
                cell.setCellValue(activity.getEditBy());
            }
        }
        //返回响应信息
        //1.设置响应类型
        response.setContentType("application/octet-stream;charset=UTF-8");
        //根据HTTP协议的规定，浏览器每次向服务器发送请求，都会把浏览器信息以请求头的形式发送到服务器
        String browser = request.getHeader("User-Agent");

        //不同的浏览器接收响应头采用的编码格式不一样：
        //IE采用 urlencoded
        ////火狐采用 ISO8859-1
        String fileName = URLEncoder.encode("市场活动列表", "UTF-8");
        if (browser.contains("firefox")) {
            //火狐采用 ISO8859-1
            fileName = new String("市场活动列表".getBytes("UTF-8"), "ISO8859-1");
        }

        //默认情况下，浏览器接收到响应信息之后，直接在显示窗口中打开；
        //可以设置响应头信息，使浏览器接收到响应信息之后，在下载窗口打开,attachment附件
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        //2.获取输出流
        OutputStream os2 = response.getOutputStream();
        //3.把excel文件通过os2输出到客户端
        wb.write(os2);
        //4.关闭资源
        os2.flush();
        wb.close();
    }


    @RequestMapping("/workbench/activity/importActivity.do")
    @ResponseBody
    public ResultEntity importActivity(MultipartFile activityFile, HttpSession session) {
        try {
            List<Activity> activityList = new ArrayList<Activity>();
            User user = (User) session.getAttribute(Constants.MESSAGE_SESSION_NAME);
            //1.根据上传文件获取输入流
            InputStream is = activityFile.getInputStream();
            //2.根据输入流获取一个工作簿对象
            HSSFWorkbook wb = new HSSFWorkbook(is);
            //3.根据工作簿对象获取一个第一个工作表对象
            HSSFSheet sheet = wb.getSheetAt(0);
            //4.根据工作表对象获取最后一行的下标，进行循环遍历每一行的数据，并把数据填充到Activity对象中，把该对象添加到list集合中
            flag:
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Activity activity = new Activity();
                //设置创建人和所有者
                activity.setCreateBy(user.getId());
                activity.setOwner(user.getId());
                //从获取第二行的数据开始遍历
                HSSFRow row = sheet.getRow(i);
                //比较开始日期和结束日期
                String startDate = null;
                String endDate = null;
                //遍历这一行的每一列数据
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    //获取每一列的单元格对象
                    HSSFCell cell = row.getCell(j);
                    //根据单元格对象获取这一个单元格的数据，使用自定义的获取数据的方法，为了将所有的数据转为String
                    String cellValue = getCellValue(cell);
                    if(cellValue == null || cellValue == ""){
                        continue flag;
                    }
                    //获取当前行的开始日期和结束日期
                    if (j == 1) {
                        startDate = cellValue;
                    }
                    if (j == 2) {
                        endDate = cellValue;
                    }
                    if (j == 0) {
                        activity.setName(cellValue);
                    } else if (j == 1) {
                        activity.setStartDate(cellValue);
                    } else if (j == 2) {
                        activity.setEndDate(cellValue);
                    } else if (j == 3) {
                        activity.setCost(cellValue);
                    } else if (j == 4) {
                        activity.setDescription(cellValue);
                    }
                }
                //比较当前日期和结束日期
                if (startDate.compareTo(endDate) > 0) {
                    //跳过当前循环，从下行数据开始
                    continue ;
                }

                activityList.add(activity);
            }

            //5.调用service层的批量增加的方法进行增加
            int saveNum = activityService.saveForList(activityList);
            return ResultEntity.successWithData(saveNum);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultEntity.failed("系统繁忙,请稍后重试");
        }
    }

    //将获取单元格对象的值类型全部转为String
    public static String getCellValue(HSSFCell cell) {
        String ret = "";

        switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_STRING:
                ret = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN:
                ret = cell.getBooleanCellValue() + "";
                break;
            case HSSFCell.CELL_TYPE_NUMERIC:
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                //如果是日期转换的数字
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    //获取日期类型的值
                    ret = sdf.format(cell.getDateCellValue());
                } else {
                    //如果是正常的数字则转为字符串
                    ret = cell.getNumericCellValue() + "";
                }
                break;
            case HSSFCell.CELL_TYPE_FORMULA:
                ret = cell.getCellFormula();
                break;
            default:
                ret = "";
        }

        return ret;
    }
}
